package com.android.kuai.zhuan.service;

import android.app.DownloadManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.android.kuai.zhuan.MyApplication;
import com.android.kuai.zhuan.R;

import com.android.kuai.zhuan.activity.MainActivity;
import com.android.kuai.zhuan.bean.AppListBean;
import com.android.kuai.zhuan.bean.UpgradeBean;
import com.android.kuai.zhuan.download.DownloadService;
import com.android.kuai.zhuan.retrofit.BaseApi;
import com.android.kuai.zhuan.retrofit.api.ApiInterface;
import com.android.kuai.zhuan.utils.CommandExecution;
import com.android.kuai.zhuan.utils.CommonUtils;
import com.android.kuai.zhuan.utils.DownloadUtils;
import com.android.kuai.zhuan.utils.FileUtil;
import com.android.kuai.zhuan.utils.HmSharedPreferencesUtils;
import com.android.kuai.zhuan.utils.ScreenUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainService extends Service {

    AutoReaderThread readerThread;
    List<String> taskList = new ArrayList<>();
    List<AppListBean.DataBean> appListData;
    List<String> appList;
    PackageManager pm;
    DownloadManager downloadManager;
    DownloadUtils downloadUtils;
    boolean runStatus = false;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        pm = getPackageManager();
        //获取DownloadManager
        downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        downloadUtils = new DownloadUtils(this);
        initRegister();
        readerThread = new AutoReaderThread();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(1, buildNotification());
        String command = "";
        if(intent != null) {
            command = intent.getStringExtra("command");
        }
        if(!TextUtils.isEmpty(command)) {
            Log.d("leihuiming", "command = " + command);
            switch (command) {
                case "start":
                    appList = intent.getStringArrayListExtra("tasklist");
                    beginScript();
                    checkYangMaoAppVersion();
                    break;
                case "daemon":
                    appList = HmSharedPreferencesUtils.getDataList("tasklist");
                    beginScript();
                    checkYangMaoAppVersion();
                    break;
                default:
                    break;
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    public void initRegister() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
        filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(receiver, filter);
    }

    public void startWork() {
        if (!MyApplication.isRunning) {
            MyApplication.isRunning = true;

            if (appList != null && appList.size() > 0) {
                taskList.clear();
                //appList = CommonUtils.RemoveDuplicates(taskList);
                for (String s : appList) {
                    taskList.add(s);
                    taskList.add(s);
                    taskList.add(s);
                }
                //checkYangMaoAppVersion();
                checkAppUpdate();
            } else {
                MyApplication.isRunning = false;
            }
        } else {

        }
    }

    private Notification buildNotification() {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this).setSmallIcon(R.mipmap.app_icon)
                .setContentTitle("服务正在运行")
                .setContentText("自动阅读服务正在运行");
        mBuilder.setTicker("服务正在运行");//第一次提示消息的时候显示在通知栏上
        mBuilder.setAutoCancel(false);//自己维护通知的消失

        //封装一个Intent
        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, new Intent(),
                PendingIntent.FLAG_UPDATE_CURRENT);
        // 设置通知主题的意图
        mBuilder.setContentIntent(resultPendingIntent);
        return mBuilder.build();
    }

    private class AutoReaderThread extends Thread {
        List<String> scripts;

        public AutoReaderThread() {
        }

        @Override
        public void run() {
            super.run();
            try {
                //beginScript();
                //runStatus = true;
                for (String pkg : taskList) {
                    Log.d("leihuiming", "script = " + MyApplication.basePath + File.separator + CommonUtils.getScriptFileName(pkg));
                    scripts = FileUtil.readLine(MyApplication.basePath + File.separator + CommonUtils.getScriptFileName(pkg));
                    if (scripts == null || scripts.size() <= 0) return;
                    String[] command;
                    for (String s : scripts) {
                        //if(!MyApplication.getReadStatus()) return;
                        //Log.d("leihuiming", "ss = " + s);
                        command = s.split("\\|");
                        //Log.d("leihuiming", "command[0] = " + command[0]);
                        CommandExecution.execCommand(command[0], true);
                        //Log.d("leihuiming", "command[1] = " + command[1].trim());
                        Thread.sleep(Integer.parseInt(command[1].trim()) * 1000);
                    }
                }
                //runStatus = false;
                MyApplication.isRunning = false;
                endScript();
                mHandler.sendEmptyMessage(MSG_COMPLETED);
            } catch (Exception e) {
                e.printStackTrace();
                //runStatus = false;
                MyApplication.isRunning = false;
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        endScript();
                    }
                }.start();
            }
        }
    }

    private void beginScript() {
        try {
            CommandExecution.execCommand("input keyevent HOME", true);
            CommandExecution.execCommand("settings put system screen_brightness_mode 0", true);
            //Thread.sleep(1000);
            CommandExecution.execCommand("settings put system screen_brightness 255", true);
            //Thread.sleep(1000);
            CommandExecution.execCommand("settings put system screen_brightness 0", true);
            //Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void endScript() {
        try {
            CommandExecution.execCommand("settings put system screen_brightness 155", true);
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkAppUpdate() {
        if (appList != null && appList.size() > 0) {
            for (String pkgName : appList) {
                getAppDetail(pkgName);
            }
        }
    }

    /**
     * 下载文件
     *
     * @param url 下载地址
     */
    private void downloadFile(String url) {
        downloadUtils.downloadAPK(url);
    }

    private void getAppList() {
        Map<String, Object> maps = new HashMap<>();
        maps.put("service", "getTaskList");
        maps.put("imei", CommonUtils.getPhoneImei());
        maps.put("width", ScreenUtils.getScreenWidth(this));
        maps.put("heigh", ScreenUtils.getScreenHeight(this));
        maps = MainService.appendParams(maps);
        //RetrofitServiceManager.getInstance().create(ApiInterface.class).getAppList(maps);
        BaseApi.request(BaseApi.createApi(ApiInterface.class).getAppList(maps), new BaseApi.IResponseListener<AppListBean>() {
            @Override
            public void onSuccess(AppListBean data) {
                Log.d("leihuiming", "json= " + MyApplication.mGson.toJson(data));
                appListData = data.getData();
                checkAppUpdate();
            }

            @Override
            public void onFail() {
                //runStatus = false;
                Toast.makeText(MainService.this, "更新应用失败，请重新开始", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void getAppDetail(final String pkgName) {
        Log.d("leihuiming", "getAppDetail  pkgName= " + pkgName);
        Map<String, Object> maps = new HashMap<>();
        maps.put("service", "getTaskInfo");
        maps.put("imei", CommonUtils.getPhoneImei());
        maps.put("width", ScreenUtils.getScreenWidth(this));
        maps.put("heigh", ScreenUtils.getScreenHeight(this));
        maps.put("package", pkgName);
        maps = MainService.appendParams(maps);
        BaseApi.request(BaseApi.createApi(ApiInterface.class).getAppList(maps), new BaseApi.IResponseListener<AppListBean>() {
            @Override
            public void onSuccess(AppListBean data) {
                Log.d("leihuiming", "getAppDetail = " + MyApplication.mGson.toJson(data));
                String version = CommonUtils.getPackageCode(MainService.this, pkgName);
                if (data.getData() == null || data.getData().size() <= 0) return;
                String newVersion = data.getData().get(0).getVersion();
                if (!version.equals(newVersion)) {
                    downloadFile(data.getData().get(0).getApk());
                }
                downloadFile(data.getData().get(0).getUrl());
            }

            @Override
            public void onFail() {

            }
        });
    }

    public void checkYangMaoAppVersion() {
        Map<String, Object> maps = new HashMap<>();
        maps.put("service", "getAppVersion");
        maps.put("imei", CommonUtils.getPhoneImei());
        maps = MainService.appendParams(maps);
        BaseApi.request(BaseApi.createApi(ApiInterface.class).getAppVersion(maps), new BaseApi.IResponseListener<UpgradeBean>() {
            @Override
            public void onSuccess(UpgradeBean data) {
                if (data.getCode() == 0 && data.getData().size() > 0) {
                    if (!CommonUtils.getPackageCode(MainService.this, getPackageName()).equals(data.getData().get(0).getVersion())) {
                        Log.d("leihuiming", "版本号不一致");
                        downloadFile(data.getData().get(0).getUrl());
                    } else {
                        Log.d("leihuiming", "版本号一致, 开始工作");
                        startWork();
                    }
                }
            }

            @Override
            public void onFail() {

            }
        });
    }

    public static Map<String, Object> appendParams(Map<String, Object> maps) {
        maps.put("info", "a20180101brush");
        maps.put("ip", "10.0.2.12");
        maps.put("mfrs", "apple");
        maps.put("model", "xiaomiNote2");
        maps.put("gps", "123.4545,60.46545");
        maps.put("idfa", "12345678");
        maps.put("idfv", "2312345");
        return maps;
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d("leihuiming", "action = " + action);
            switch (action) {
                case DownloadManager.ACTION_DOWNLOAD_COMPLETE:
                    long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(downloadId);
                    Cursor c = downloadManager.query(query);
                    if (c.moveToFirst()) {
                        if (downloadUtils.downloadIds.contains(downloadId)) {
                            String path = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                            Log.d("leihuiming", "dowload file path = " + path);
                            if (path.endsWith("apk")) {
                                Message msg = Message.obtain();
                                msg.what = MSG_INSTALL_APP;
                                msg.obj = path;
                                mHandler.sendMessage(msg);
                            } else {
                                installCount++;
                                if (installCount == downloadUtils.downloadIds.size()) {
                                    downloadUtils.downloadIds.clear();
                                    mHandler.sendEmptyMessageDelayed(MSG_START_READ, 10000);
                                    installCount = 0;
                                }
                            }
                        }
                    }
                    c.close();
                    break;
                case Intent.ACTION_PACKAGE_ADDED:
                    break;
                case Intent.ACTION_PACKAGE_REPLACED:
                    break;
                default:
                    break;
            }
        }
    };


    final int MSG_INSTALL_APP = 1;
    final int MSG_START_READ = 2;
    final int MSG_COMPLETED = 3;
    int installCount = 0;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_INSTALL_APP:
                    final String path = (String) msg.obj;
                    if (!TextUtils.isEmpty(path)) {
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                installCount++;
                                Log.d("leihuiming", "installcount=" + installCount);
                                CommandExecution.execCommand("pm install -r " + path, true);
                                Log.d("leihuiming", "downloadid size = " + downloadUtils.downloadIds.size());
                                if (installCount == downloadUtils.downloadIds.size()) {
                                    downloadUtils.downloadIds.clear();
                                    mHandler.sendEmptyMessageDelayed(MSG_START_READ, 10000);
                                    installCount = 0;
                                }
                            }
                        }.start();
                    }
                    break;
                case MSG_START_READ:
                    Collections.shuffle(taskList);
                    Log.d("leihuiming", "MSG_START_READ taskList size = " + taskList.size());
                    readerThread = new AutoReaderThread();
                    readerThread.start();
                    break;
                case MSG_COMPLETED:
                    Log.d("leihuiming", "MSG_COMPLETED");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("leihuiming", "reader service onDestroy");
    }
}
